﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using QuanCafe.DataLayer;
using QuanCafe.BusinessLayer;

namespace QuanCafe.admin
{
    public partial class Item : System.Web.UI.Page
    {
        string strImageURL = "";
        string strFileName = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.fnLoadData();
                LoadCbo();
            }
            LoadDistrict();
        }

        private void LoadCbo()
        {
            QuanCafe.BusinessLayer.ItemType ItemType = new QuanCafe.BusinessLayer.ItemType();
            cboItemTypeID.DataSource = ItemType.GetAll();
            cboItemTypeID.DataTextField = "ItemTypeName";
            cboItemTypeID.DataValueField = "ItemTypeID";
            cboItemTypeID.DataBind();

            QuanCafe.BusinessLayer.Level Level = new QuanCafe.BusinessLayer.Level();
            cboLevelID.DataSource = Level.GetAll();
            cboLevelID.DataTextField = "LevelName";
            cboLevelID.DataValueField = "LevelID";
            cboLevelID.DataBind();

            QuanCafe.BusinessLayer.Province Province = new QuanCafe.BusinessLayer.Province();
            cboProvinceID.DataSource = Province.GetAll();
            cboProvinceID.DataTextField = "ProvinceName";
            cboProvinceID.DataValueField = "ProvinceID";
            cboProvinceID.DataBind();
            LoadDistrict(); 
        }

        private void LoadDistrict()
        {
            if (cboProvinceID.SelectedValue.ToString() != "0")
            {
                QuanCafe.BusinessLayer.District District = new QuanCafe.BusinessLayer.District();
                cboDistrictID.DataSource = District.GetByProvinceID(int.Parse(cboProvinceID.SelectedValue.ToString()));
                cboDistrictID.DataTextField = "DistrictName";
                cboDistrictID.DataValueField = "DistrictID";
                cboDistrictID.DataBind();
            }

        }
        /// <summary>
        /// load data
        /// </summary>
        private void fnLoadData()
        {
            try
            {
                QuanCafe.BusinessLayer.Item Item = new QuanCafe.BusinessLayer.Item();
                DataTable dtb = Item.GetAll();
                dtgItem.DataSource = dtb;
                dtgItem.DataBind();
                for (int i = 0; i < dtgItem.Items.Count; i++)
                {
                    if (dtb.Rows[i]["Status"].ToString() == "1")
                    {
                        ((ImageButton)dtgItem.Items[i].FindControl("btnActive")).ImageUrl = "~/Images/icons/btnOK.jpg";
                    }
                    else
                    {
                        ((ImageButton)dtgItem.Items[i].FindControl("btnActive")).ImageUrl = "~/Images/icons/btnKO.jpg";
                    }
                }
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }
        public void fnClearControl()
        {
            txtItemID.Text = "";
            txtAddress.Text = "";
            txtEmail.Text = "";
            txtItemDesc.Text = "";
            txtItemTitle.Text = "";
            txtImageName.Text = "";
            imgBox.ImageUrl = "~/images/icons/NoImage.JPG";
            txtPassword.Text = "";
            txtTag.Text = "";
            txtTagWithoutSign.Text = "";
            txtWebLink.Text = "";
            lblError.Text = "";
            edtContent.Value = "";
            btnChangePicture.Visible = false;
            txtFileImageUpLoad.Visible = true;
        }
        protected void btnAddItem_Click(object sender, EventArgs e)
        {
            fnClearControl();
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                QuanCafe.BusinessLayer.Item ItemObj = new QuanCafe.BusinessLayer.Item();
                if (txtItemID.Text == "") // Insert
                {
                    CLSCommon.DeleteImage(txtImageName.Text, ConfigurationManager.AppSettings["ItemsMap"].ToString(), this);
                    uploadPic();

                    //Save Thong tin San pham 
                    ItemObj.activity = "Insert";
                    ItemObj.Address = txtAddress.Text.Trim();
                    ItemObj.Creator = Session["AdminName"].ToString();
                    ItemObj.DistrictID = int.Parse(cboDistrictID.SelectedValue.ToString());
                    ItemObj.Email = txtEmail.Text.Trim();
                    ItemObj.ItemContent = edtContent.Value.ToString();
                    ItemObj.ItemDesc = txtItemDesc.Text.Trim();
                    ItemObj.ItemTitle = txtItemTitle.Text.Trim();
                    ItemObj.ItemTypeID = int.Parse(cboItemTypeID.SelectedValue.ToString());
                    ItemObj.LevelID = int.Parse(cboLevelID.SelectedValue.ToString());
                    ItemObj.LinkMapImage = strImageURL;
                    ItemObj.Password = txtPassword.Text.Trim();
                    //ItemObj.Permission
                    ItemObj.ProvinceID = int.Parse(cboProvinceID.SelectedValue.ToString());
                    ItemObj.Tag =txtTag.Text.Trim();
                    ItemObj.TagWithoutSign =  txtTagWithoutSign.Text.Trim();
                    ItemObj.WebLink = txtWebLink.Text.Trim();                     
                    ItemObj.InsertUpdate();
                    fnLoadData();
                    lblError.Text = "Thêm mới thành công";
                    fnClearControl();
                }
                else
                {
                    if (btnChangePicture.Visible == false && txtFileImageUpLoad.FileName != "")
                    {
                        //Xoa hinh da update tu truoc
                        CLSCommon.DeleteImage(txtImageName.Text, ConfigurationManager.AppSettings["ItemsMap"].ToString(), this);
                        uploadPic();
                    }
                    ItemObj.activity = "Update";
                    //Save Thong tin San pham 
                    ItemObj.ItemID = int.Parse(txtItemID.Text.Trim());
                    ItemObj.Address = txtAddress.Text.Trim();
                    ItemObj.Creator = Session["AdminName"].ToString();
                    ItemObj.DistrictID = int.Parse(cboDistrictID.SelectedValue.ToString());
                    ItemObj.Email = txtEmail.Text.Trim();
                    ItemObj.ItemContent = edtContent.Value.ToString();
                    ItemObj.ItemDesc = txtItemDesc.Text.Trim();
                    ItemObj.ItemTitle = txtItemTitle.Text.Trim();
                    ItemObj.ItemTypeID = int.Parse(cboItemTypeID.SelectedValue.ToString());
                    ItemObj.LevelID = int.Parse(cboLevelID.SelectedValue.ToString());
                    ItemObj.LinkMapImage = strImageURL;
                    ItemObj.Password = txtPassword.Text.Trim();
                    //ItemObj.Permission
                    ItemObj.ProvinceID = int.Parse(cboProvinceID.SelectedValue.ToString());
                    ItemObj.Tag = txtTag.Text.Trim();
                    ItemObj.TagWithoutSign = txtTagWithoutSign.Text.Trim();
                    ItemObj.WebLink = txtWebLink.Text.Trim();
                    ItemObj.InsertUpdate();
                    fnLoadData();
                    lblError.Text = "Cập nhập thành công";
                    fnClearControl();
                }
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }

        private void uploadPic()
        {            
            if (txtFileImageUpLoad.FileName != "")
            {
                string a = txtFileImageUpLoad.FileName;
                //---------------------------------
                string mext = "";
                mext = a.Substring(a.LastIndexOf("."));
                if (mext != ".png" && mext != ".gif" && mext != ".jpeg" && mext != ".jpg" && mext != ".bmp" && mext != ".GIF" && mext != ".JPEG" && mext != ".JPG" && mext != ".BMP")
                {
                    this.lblError.Text = "Tập tin upload không phải tập tin dạng hình.";
                    return;
                }
                // Kiem tra Dung luong hinh nho Hon 200kb
                int intMaxImageSize = Convert.ToInt32(ConfigurationSettings.AppSettings["MaxUploadImageSize"].Trim()) * 1024;
                int filesize = txtFileImageUpLoad.PostedFile.ContentLength;
                if (filesize > intMaxImageSize)
                {
                    lblError.Text = "Dung lượng tập tin Upload đã vượt quá quy định cho phép(200kb).";
                    return;
                }
                //End Kiem tra Dung luong hinh nho Hon 200kb
                strFileName = CLSCommon.UploadImage(txtFileImageUpLoad, "ItemsMap", "ItemsImage", this);
                strImageURL = "~" + ConfigurationManager.AppSettings["Itemsmap"].ToString() + strFileName;

            }
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                string strID = "";
                for (int i = 0; i < dtgItem.Items.Count; i++)
                {
                    if (((CheckBox)dtgItem.Items[i].FindControl("chkSelect")).Checked == true)
                    {
                        strID += dtgItem.Items[i].Cells[0].Text.Trim() + "$";//Cot dau tien phai de cai ID                         
                    }
                }
                CLSCommon.DeleteListRecord("SP_Item", strID, "ItemID");
                fnLoadData();
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }
        public void fnLoadDataByID(int IntID)
        {
            try
            {
                QuanCafe.BusinessLayer.Item Item = new QuanCafe.BusinessLayer.Item();
                Item.ItemID = IntID;
                DataRow dr = Item.GetByID();
                txtItemID.Text = IntID.ToString();
                txtEmail.Text = dr["Email"].ToString();
                txtPassword.Text = dr["Password"].ToString();
                cboItemTypeID.SelectedValue = dr["ItemTypeID"].ToString();
                cboLevelID.SelectedValue = dr["LevelID"].ToString();
                txtAddress.Text = dr["Address"].ToString();
                cboProvinceID.SelectedValue = dr["ProvinceID"].ToString();
                LoadDistrict();
                cboDistrictID.SelectedValue = dr["DistrictID"].ToString();
                imgBox.ImageUrl = dr["LinkMapImage"].ToString();
                txtWebLink.Text = dr["WebLink"].ToString();
                txtTag.Text = dr["Tag"].ToString();
                txtTagWithoutSign.Text = dr["TagWithoutSign"].ToString();
                txtItemTitle.Text = dr["ItemTitle"].ToString();
                txtItemDesc.Text = dr["ItemDesc"].ToString();
                edtContent.Value = dr["ItemContent"].ToString();
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }

        protected void dtgItem_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            string nName = e.CommandName.ToLower();
            int ID = -1;
            switch (nName)
            {
                case "edit":
                    ID = Convert.ToInt32(dtgItem.Items[e.Item.ItemIndex].Cells[0].Text);
                    fnLoadDataByID(ID);
                    break;
                case "activechange":
                    ID = Convert.ToInt32(dtgItem.Items[e.Item.ItemIndex].Cells[0].Text);
                    QuanCafe.BusinessLayer.Item Item = new QuanCafe.BusinessLayer.Item();
                    Item.ItemID = ID;
                    Item.ChangeActive();
                    break;
            }
            this.fnLoadData();
        }

        protected void dtgItem_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
        {
            dtgItem.CurrentPageIndex = e.NewPageIndex;
            this.fnLoadData();
        }

        protected void btnChangePicture_Click(object sender, EventArgs e)
        {
            try
            {
                txtFileImageUpLoad.Visible = true;
                imgBox.ImageUrl = strImageURL;
                //imgBox.ImageUrl = Page.ResolveUrl("~/images/icons/NoImage.JPG");
                btnChangePicture.Visible = false;
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message.ToString();
            }
        }
        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            this.fnClearControl();
        }
    }
}
